﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PortalWeb.CMS.Core.Entity;
using PortalWeb.CMS.Business;
using PortalWeb.Common;
using PortalWeb.Common.Config;
using PortalWeb.Models.Cms;

namespace PortalWeb.CMS.Web.Areas.Admin.Controllers
{
    [Authorize]
    public class AttachmentController : Controller
    {
        public AttachmentController(AttachmentManager attachmentManager)
        {
            AttachmentManager = attachmentManager;
        }

        public AttachmentManager AttachmentManager { get; private set; }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        public ActionResult Upload()
        {
             var uploadConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~").GetSection("UploadConfig") as
                    UploadConfig;
            //文件最大限制
            int maxSize = uploadConfig.MaxSize;
            //保存路径
            //文件路径
            string fileParth = "~/" + uploadConfig.Path + "/";


            //文件类型
            string _dirName;
            //允许上传的类型
            Hashtable extTable = new Hashtable();
            extTable.Add("image", uploadConfig.ImageExt);
            extTable.Add("flash", uploadConfig.FileExt);
            extTable.Add("media", uploadConfig.MediaExt);
            extTable.Add("file", uploadConfig.FileExt);
            //上传的文件
            HttpPostedFileBase _postFile = Request.Files["imgFile"];
            if (_postFile == null) return Json(new {error = '1', message = "请选择文件"});

            //文件名
            string fileName = _postFile.FileName;
            //扩展名
            string fileExt = Path.GetExtension(fileName).ToLower();
            //文件类型
            _dirName = Request.QueryString["dir"];
            if (string.IsNullOrEmpty(_dirName))
            {
                _dirName = "image";
            }
            if (!extTable.ContainsKey(_dirName)) return Json(new {error = 1, message = "目录类型不存在"});
            //文件大小
            if (_postFile.InputStream == null || _postFile.InputStream.Length > maxSize)
                return Json(new {error = 1, message = "文件大小超过限制"});
            //检查扩展名
            if (string.IsNullOrEmpty(fileExt) ||
                Array.IndexOf(((string) extTable[_dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
                return Json(new {error = 1, message = "不允许上传此类型的文件。 \n只允许" + ((String) extTable[_dirName]) + "格式。"});
            fileParth += _dirName + "/" + DateTime.Now.ToString("yyyy-MM") + "/";
            string _savePath = Server.MapPath(fileParth);
            //检查上传目录
            if (!Directory.Exists(_savePath)) Directory.CreateDirectory(_savePath);
            string _newFileName = DateTime.Now.ToString("yyyyMMdd_hhmmss") + fileExt;
            _savePath += _newFileName;
            fileParth += _newFileName;
            //保存文件
            _postFile.SaveAs(_savePath);
            //保存数据库记录
            AttachmentManager.Add(new Attachment()
            {
                Extension = fileExt.Substring(1),
                FileParth = fileParth,
                Owner = User.Identity.Name,
                UploadDate = DateTime.Now,
                Type = _dirName
            });
            return Json(new {error = 0, url = Url.Content(fileParth)});
        }

        /// <summary>
        /// 附件管理列表
        /// </summary>
        /// <param name="id">公共模型ID</param>
        /// <param name="dir">目录（类型）</param>
        /// <returns></returns>
        public ActionResult FileManagerJson(int? id, string dir)
        {
            AttachmentManagerViewModel _attachmentViewModel;
            IEnumerable<Attachment> attachments;

            if (id == null)
            {
                //id为null，表示是公共模型id为null，此时查询数据库中没有跟模型对应起来的附件列表（以上传，但上传的文章……还未保存）
                attachments = AttachmentManager.FindList(null, User.Identity.Name, dir);
            }
            else
            {
                //id不为null，返回指定模型id和id为null（新上传的）附件了列表
                attachments = AttachmentManager.FindList((int) id, User.Identity.Name, dir, true);
            }
            //循环构造AttachmentManagerViewModel
            var attachmentList = new List<AttachmentManagerViewModel>(attachments.Count());
            foreach (var attachment in attachments)
            {
                _attachmentViewModel = new AttachmentManagerViewModel() { datetime = attachment.UploadDate.ToString("yyyy-MM-dd HH:mm:ss"), filetype = attachment.Extension, has_file = false, is_dir = false, is_photo = attachment.Type.ToLower() == "image" ? true : false, filename = Url.Content(attachment.FileParth) };
                var fileInfo = new FileInfo(Server.MapPath(attachment.FileParth));
                _attachmentViewModel.filesize = (int)fileInfo.Length;
                attachmentList.Add(_attachmentViewModel);
            }
            return Json(new { moveup_dir_path = "", current_dir_path = "", current_url = "", total_count = attachmentList.Count, file_list = attachmentList }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 创建缩略图
        /// </summary>
        /// <param name="originalPicture">原图地址</param>
        /// <returns>缩略图地址。生成失败返回null</returns>
        public ActionResult CreateThumbnail(string originalPicture)
        {
            //原图为缩略图直接返回其地址
            if (originalPicture.IndexOf("_s", System.StringComparison.Ordinal) > 0) return Json(originalPicture);
            //缩略图地址
            string thumbnail = originalPicture.Insert(originalPicture.LastIndexOf('.'), "_s");
            //创建缩略图
            if (Picture.CreateThumbnail(Server.MapPath(originalPicture), Server.MapPath(thumbnail), 160, 120))
            {
                //记录保存在数据库中
                AttachmentManager.Add(new Attachment() { Extension = thumbnail.Substring(thumbnail.LastIndexOf('.') + 1), FileParth = "~" + thumbnail, Owner = User.Identity.Name, Type = "image", UploadDate = DateTime.Now });
                return Json(thumbnail);
            }
            return Json(null);
        }
    }
}